package com.lijiayuedaren.service;

import com.lijiayuedaren.dao.ImgNameDao;
import com.lijiayuedaren.entity.Image;
import com.lijiayuedaren.entity.PageBean;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;

public class ImgNameService {
    protected ImgNameDao dao =  new ImgNameDao();
    public void saveName()  {
        File allFile = new File("D:\\手机备份\\Telegram\\Telegram Images");
        File[] files = allFile.listFiles();
        for (File file : files) {
            String name = file.getName();
            Date lastModified = new Date(file.lastModified());
            int size = (int) file.length();
            BufferedImage sourceImg = null;
            try {
                sourceImg = ImageIO.read(new FileInputStream(file));
            } catch (Exception e) {
                System.out.println("------------");
                System.out.println(name+"读写失败");
                e.printStackTrace();
                continue;
            }
            int height = sourceImg.getHeight();
            int width = sourceImg.getWidth();
            double ratio = 1.0 * height / width;
            dao.saveName(name,width,height,ratio,size,lastModified);
        }
    }

    public PageBean<Image> getImage(int current) {
        PageBean<Image> pageBean = new PageBean<>();
        pageBean.setSize(20);
        pageBean.setCurrent(current);
        String type = "ratio";
        List<Image> images = dao.getImage(type,current, pageBean.getSize());
        pageBean.setCount(dao.getCount());
        pageBean.setData(images);
        return pageBean;

    }
//随机获得一组图片
    public List<Image> getRandomList() {
        Random random = new Random();
        //得到一组随机图片id
        String[] ids = new String[20];
        int count = dao.getCount();
        for (int i = 0; i < ids.length; i++) {
            ids[i]= String.valueOf(random.nextInt(count));
        }
        //打印id
        System.out.println(Arrays.toString(ids));
        //获取指定id的图片
        List<Image> imgs = dao.getImageById(ids);
        //将这一批id的图片的hadseem设置为1
        dao.setHadSeem(ids);
        return imgs;
    }

    //根据id删除指定图片
    public void deleteImage(int id) {
        String name = dao.getOneImageName(id);
        dao.saveDelete(name,id);
        System.out.println("删除图片:"+name);
        File file = new File("D:\\手机备份\\Telegram\\Telegram Images\\"+name);
        file.delete();
        dao.deleteImage(id);
    }

}
